
var express = require('express');
var router = express.Router();
var db = require("../db")
var log = require("log4js").getLogger("index")

var RECORD_PER_PAGE = 1; //每页记录数
/**
 * 构建错误响应
 */
function _err(code, desc) {
  return { err_code: code, err_desc: desc };
}

function _ok(data) {
  return { err_code: 0, data: data };
}

function processErr(err, res) {
  if (err) {
    res.json(_err(-1, err.toString()))
    res.end();
    return true;
  } else
    return false;
}
/* 查询店铺列表 */
router.get('/shop', function (req, res, next) {
  db.execute("select * from ld_shop", function (err, rows) {
    if (err)
      res.json(_err(-1, err.toString()))
    else
      res.json(_ok(rows))
    res.end()
  })
});


/* 查询店铺列表分页演示 */
router.get('/shoppage', function (req, res, next) {

  db.query("ld_shop", function (err, total, next) {
    if (processErr(err, res)) return;
    var page = req.query.page ? parseInt(req.query.page) : 1;
    next((page - 1) * RECORD_PER_PAGE, RECORD_PER_PAGE, function (err, rows) {
      if (processErr(err, res)) return;
      res.json(_ok({ total: total, page: page, data: rows }))
      res.end()
    })

  })
});

/* 新增店铺 */
router.post('/shop', function (req, res, next) {
  var data = { shop_name: req.body.shop_name, shop_address: req.body.shop_address, shop_telephone: req.body.shop_telephone }
  var sql = "insert into ld_shop set ?"
  db.execute(sql, data, function (err, rows) {
    if (processErr(err, res)) return;
    res.json(_ok(null))
    res.end()
  })
});

/* 修改店铺列表 */
router.put('/shop/:id', function (req, res, next) {
  var data = [req.body.shop_name, req.body.shop_address, req.body.shop_telephone, req.params.id]
  log.debug(JSON.stringify(data));
  var sql = "update ld_shop set shop_name = ?, shop_address = ?, shop_telephone = ? where id = ?"
  db.execute(sql, data, function (err, rows) {
    if (processErr(err, res)) return;
    res.json(_ok(null))
    res.end()
  })
});

/* 删除店铺 */
router.delete('/shop/:id', function (req, res, next) {
  db.execute("delete from ld_shop where id=?", [req.params.id], function (err, rows) {
    if (processErr(err, res)) return;
    res.json(_ok(null))
    res.end()
  })
});



module.exports = router;
